//
//  MVCViewController.m
//  MV_C_P_VM
//
//  Created by Willian on 2021/4/29.
//

#import "MVCViewController.h"

#import "CommonHeader.h"

#import "MVCLoginView.h"
#import "MVCLoginModel.h"

@interface MVCViewController () <UITextFieldDelegate>

@property (nonatomic, strong) MVCLoginView *loginView;
@property (nonatomic, strong) MVCLoginModel *loginModel;

@end

@implementation MVCViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //模型
    self.loginModel = [[MVCLoginModel alloc] init];
    
    //视图
    self.loginView = [[MVCLoginView alloc] initWithFrame:CGRectMake(0, 50, [UIScreen mainScreen].bounds.size.width, 400)];
    self.loginView.usernameTextField.delegate = self;
    self.loginView.passwordTextField.delegate = self;
    [self.view addSubview:self.loginView];
    
    [self.loginView.loginButton addTarget:self action:@selector(loginButtonClick) forControlEvents:UIControlEventTouchUpInside];
    
    //按钮先不可点击
    self.loginView.usernameTextField.backgroundColor = WhiteBgColor;
    self.loginView.passwordTextField.backgroundColor = WhiteBgColor;
    self.loginView.loginButton.enabled = NO;
}

- (void)loginButtonClick{
    NSLog(@"登录按钮点击了");
}

#pragma mark - UITextFieldDelegate  view->model model->view都是控制器处理
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(nonnull NSString *)string
{
    //OC中 字符串的拼接
    if (textField == self.loginView.usernameTextField) {
        self.loginModel.userName = [textField.text stringByReplacingCharactersInRange:range withString:string];
    } else {
        self.loginModel.password = [textField.text stringByReplacingCharactersInRange:range withString:string];
    }
    
    BOOL enableLogin = YES;
    if ([self.loginModel.userName length] >= 4 && [self.loginModel.userName length] <= 16) {
        self.loginView.usernameTextField.backgroundColor = GreenBgColor;
    } else {
        if ([self.loginModel.userName length] == 0) {
            self.loginView.usernameTextField.backgroundColor = WhiteBgColor;
        } else {
            self.loginView.usernameTextField.backgroundColor = RedBgColor;
        }
        enableLogin = NO;
    }
    
    if ([self.loginModel.password length] >= 8 && [self.loginModel.password length] <= 16) {
        self.loginView.passwordTextField.backgroundColor = GreenBgColor;
    } else {
        if ([self.loginModel.password length] == 0) {
            self.loginView.passwordTextField.backgroundColor = WhiteBgColor;
        } else {
            self.loginView.passwordTextField.backgroundColor = RedBgColor;
        }
        enableLogin = NO;
    }
    
    self.loginView.loginButton.enabled = enableLogin;
    
    return YES;
}


@end

